<template>
  <div class="api-doc-container">
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    <div v-else-if="error" class="error-container">
      <div class="error-text">{{ error }}</div>
      <button class="btn btn-primary" @click="fetchApiDetail">重新加载</button>
    </div>
    <div v-else>
      <div class="api-header">
        <div class="api-name">{{ apiDetail.name || '未命名接口' }}</div>
        <div class="api-path-row">
          <div class="method-type" :class="apiDetail.method || 'OTHER'">{{ apiDetail.method || 'OTHER' }}</div>
          <div class="api-path">{{ apiDetail.path || '' }}</div>
        </div>
        <div class="api-description">{{ apiDetail.description || '暂无描述' }}</div>
      </div>
      
      <!-- 请求参数表格 -->
      <div v-if="hasRequestParams" class="section-title">请求参数</div>
      <div v-if="hasRequestParams">        
        <!-- 请求体参数 -->
        <template v-if="requestBodyParams.length > 0">
          <template v-for="param in requestBodyParams" :key="param.type">
          <div class="model-type" style="margin-top: 16px;">{{ param.type }}</div>
          <table class="api-table">
            <thead>
              <tr>
                <th>参数名</th>
                <th>类型</th>
                <th>必填</th>
                <th>默认值</th>
                <th>示例</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in param.params" :key="item.type">
                <td>{{ item.name || '-' }}</td>
                <td>{{ item.simpleType }}</td>
                <td>{{ item.required ? '是' : '否' }}</td>
                <td>{{ item.defaultValue || '-' }}</td>
                <td>{{ item.example || '-' }}</td>
                <td>{{ item.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
          </template>
        </template>
      </div>
      
      <!-- 请求头 -->
      <div v-if="apiDetail.headers && apiDetail.headers.length > 0" class="section-title">请求头</div>
      <table v-if="apiDetail.headers && apiDetail.headers.length > 0" class="api-table">
        <thead><tr><th>名称</th><th>值</th><th>描述</th></tr></thead>
        <tbody>
          <tr v-for="header in apiDetail.headers" :key="header.name">
            <td>{{ header.name || '-' }}</td>
            <td>{{ header.value || '-' }}</td>
            <td>{{ header.description || '-' }}</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 响应参数表格 -->
      <div v-if="responseBodyParams.length > 0" class="section-title">响应参数</div>
      <div v-if="responseBodyParams.length > 0">
        <template v-if="responseBodyParams.length > 0">
          <template v-for="param in responseBodyParams" :key="param.type">
          <div class="model-type" style="margin-top: 16px;">{{ param.type }}</div>
          <table class="api-table">
            <thead>
              <tr>
                <th>参数名</th>
                <th>类型</th>
                <th>必填</th>
                <th>默认值</th>
                <th>示例</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in param.params" :key="item.type">
                <td>{{ item.name || '-' }}</td>
                <td>{{ item.simpleType }}</td>
                <td>{{ item.required ? '是' : '否' }}</td>
                <td>{{ item.defaultValue || '-' }}</td>
                <td>{{ item.example || '-' }}</td>
                <td>{{ item.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
          </template>
        </template>

      </div>
      
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, PropType } from 'vue';
import type { SimpleApiInfo, ApiInfo, ApiParam, ApiModel } from '../api/model';
import { ApiService } from '../api/services/apiService';

// Props定义
const props = defineProps<{
  currentApi: SimpleApiInfo
}>();

// 响应式数据
const apiDetail = ref<ApiInfo>({} as ApiInfo);
const loading = ref(false);
const error = ref('');

interface FlattenParams {
  params: ApiParam[];
  type: string;
}

const requestBodyParams = ref<FlattenParams[]>([]);
const responseBodyParams = ref<FlattenParams[]>([]);


// 从接口获取API详情
const fetchApiDetail = async () => {
  if (!props.currentApi || !props.currentApi.id) return;
  
  loading.value = true;
  error.value = '';
  
  try {
    const detailData = await ApiService.getApiDetail(props.currentApi.id);
    apiDetail.value = {
      ...props.currentApi,
      ...detailData
    };
    // 处理请求体参数
    if (apiDetail.value.requestBodyModel && apiDetail.value.requestBodyModel.params && Array.isArray(apiDetail.value.requestBodyModel.params)) {
      const nestedParams = flattenParams(apiDetail.value.requestBodyModel.params as ApiParam[], apiDetail.value.requestBodyModel.type);
      requestBodyParams.value = nestedParams;
    }
    // 处理响应体参数
    if (apiDetail.value.responseModel && apiDetail.value.responseModel.params && Array.isArray(apiDetail.value.responseModel.params)) {
      const nestedParams = flattenParams(apiDetail.value.responseModel.params as ApiParam[], apiDetail.value.responseModel.type);
      responseBodyParams.value = nestedParams;
    }
  } catch (err) {
    console.error('获取API详情失败:', err);
    error.value = '获取API详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 扁平化嵌套参数
const flattenParams = (params: ApiParam[], type: string = ''): FlattenParams[] => {
  let result: FlattenParams[] = [];
  const flattenParam: FlattenParams = {
    params,
    type
  };
  result.push(flattenParam);
  params.forEach((param: ApiParam) => {
    // 安全检查nestedFields
    if (param.nestedFields && Array.isArray(param.nestedFields) && param.nestedFields.length > 0) {
      // 追加进入结果数组
      const nestedParams = flattenParams(param.nestedFields, param.fullType);
      result.push(...nestedParams); 
    }
  });
  
  return result;
};

// 计算属性：是否有请求参数
const hasRequestParams = computed(() => {
  // 检查URL参数
  const hasUrlParams = apiDetail.value.parameters && apiDetail.value.parameters.length > 0;
  // 检查请求体参数
  const hasRequestBodyParams = apiDetail.value.requestBodyModel && 
                               apiDetail.value.requestBodyModel.params && 
                               apiDetail.value.requestBodyModel.params.length > 0;
  
  return hasUrlParams || hasRequestBodyParams;
});


const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  toast.textContent = message;
  toast.style.position = 'fixed';
  toast.style.top = '20px';
  toast.style.right = '20px';
  toast.style.padding = '12px 20px';
  toast.style.borderRadius = '4px';
  toast.style.color = 'white';
  toast.style.backgroundColor = type === 'success' ? '#4CAF50' : '#f44336';
  toast.style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)';
  toast.style.zIndex = '9999';
  toast.style.opacity = '0';
  toast.style.transition = 'opacity 0.3s ease';
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.style.opacity = '1';
  }, 10);
  
  setTimeout(() => {
    toast.style.opacity = '0';
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 300);
  }, 3000);
};

// 监听currentApi变化
watch(() => props.currentApi, () => {
  fetchApiDetail();
}, { deep: true, immediate: true });
</script>

<style scoped>
/* API文档样式 */
.api-doc-container {
  width: 100%;
  padding: 20px;
}

.api-header {
  margin-bottom: 20px;
}

.api-name {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--heading-color);
}

.api-path-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}

.api-path {
  font-size: 14px;
  color: var(--theme-color);
  background-color: var(--code-bg);
  padding: 8px 12px;
  border-radius: 4px;
  word-break: break-all;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: var(--text-muted);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border-color);
  border-top-color: var(--theme-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #f44336;
  text-align: center;
}

.error-text {
  font-size: 14px;
  margin-bottom: 16px;
}

/* 模型类型样式 */
.model-type {
  font-size: 13px;
  color: var(--text-muted);
  margin-bottom: 8px;
  font-style: italic;
}

/* 确保嵌套表格样式正确 */
:deep(.nested-container) {
  margin-left: 20px;
  margin-top: 16px;
  border-left: 2px solid var(--border-color);
  padding-left: 16px;
}

:deep(.nested-type) {
  font-size: 13px;
  color: var(--text-muted);
  margin-bottom: 8px;
  font-style: italic;
}

.api-description {
  color: var(--text-muted);
  line-height: 1.6;
  margin-bottom: 15px;
  font-size: 14px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 24px 0 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color);
  color: var(--heading-color);
}

.method-type {
  padding: 3px 8px;
  border-radius: 3px;
  color: white;
  font-size: 11px;
  font-weight: 600;
  margin-right: 8px;
  min-width: 50px;
  text-align: center;
}

.method-type.GET {
  background-color: #61affe;
}

.method-type.POST {
  background-color: #49cc90;
}

.method-type.PUT {
  background-color: #fca130;
}

.method-type.DELETE {
  background-color: #f93e3e;
}

.method-type.OTHER {
  background-color: #9013fe;
}

/* 表格样式 */
.api-table {
  width: 100%;
  border-collapse: collapse;
  margin: 12px 0;
  font-size: 14px;
}

.api-table th,
.api-table td {
  padding: 8px 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.api-table th {
  background-color: var(--background-color);
  font-weight: 500;
}

/* 响应示例样式 */
.response-container {
  margin-bottom: 16px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  overflow: hidden;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: var(--background-color);
  border-bottom: 1px solid var(--border-color);
}

.response-content {
  padding: 12px;
  background-color: var(--code-bg);
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  overflow-x: auto;
}

.copy-btn {
  padding: 4px 8px;
  font-size: 12px;
  background-color: var(--theme-color);
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.copy-btn:hover {
  opacity: 0.9;
}
</style>